﻿using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;

namespace JuCheap.Core.IdentityServer
{
    /// <summary>
    /// Profile service for test users
    /// </summary>
    /// <seealso cref="IdentityServer4.Services.IProfileService" />
    public class JuCheapUserProfileService : IProfileService
    {
        /// <summary>
        /// The logger
        /// </summary>
        protected readonly ILogger Logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="JuCheapUserProfileService"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public JuCheapUserProfileService(ILogger<JuCheapUserProfileService> logger)
        {
            Logger = logger;
        }

        /// <summary>
        /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            //此处还可以验证当前用户，是否有此Client的登录授权。如下
            //if (!await _userService.HasClient(context.Client.ClientId, userId))
            //{
            //    throw new Exception("您没有访问此应用的权限");
            //}

            //depending on the scope accessing the user data.
            var claims = context.Subject.Claims.ToList();
            //JWT里面只存放了一些不敏感的信息 比如一些重要的信息是用户发起请求 验证身份成功 再去 ProfileService 中把敏感信息放到HttpContext中   比如租户ID 等

            //set issued claims to return
            context.IssuedClaims = claims.ToList();

            await Task.FromResult(0);
        }

        /// <summary>
        /// This method gets called whenever identity server needs to determine if the user is valid or active (e.g. if the user's account has been deactivated since they logged in).
        /// (e.g. during token issuance or validation).
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task IsActiveAsync(IsActiveContext context)
        {
            context.IsActive = true;

            await Task.FromResult(0);
        }
    }
}